package com.hpdz.hotel_back.controller;

import com.hpdz.hotel_back.entity.Customer;
import com.hpdz.hotel_back.entity.Human;
import com.hpdz.hotel_back.service.AdminService;
import com.hpdz.hotel_back.service.CommonService;
import com.hpdz.hotel_back.service.CustomerService;
import com.hpdz.hotel_back.service.EmployeeService;
import com.hpdz.hotel_back.utils.EMUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 *  此控制器,用于实现 忘记密码邮箱验证功能!
 */

@RestController
public class CommonController {

    private final Integer mod =  100000;

    @Autowired
    private CommonService commonService;

    /**
     * 接口 1: 忘记密码,邮箱验证!
     *
     * name: /email_code
     *
     * method: post;
     *
     * parameter: email;
     *
     * return true/false;
     */
    public Boolean emailCode(String email, HttpServletRequest request){
        String code = String.valueOf(System.currentTimeMillis()%mod);
        HttpSession session = request.getSession();
        session.setAttribute(email,code);
        new EMUtils(email,code).run();
        return true;
    }

    /**
     * 接口 2: 验证代码验证!
     *
     * name: /check_code
     *
     * method: post;
     *
     * parameter: email,code;
     *
     * return true/false;
     */
    @PostMapping("/check_code")
    public Boolean checkCode(String email,String code,HttpSession session){
        String sessionAttribute = (String) session.getAttribute(email);
        if(sessionAttribute == null || !code.equals(sessionAttribute)) return false;
        Human theMan = commonService.findTheMan(email);
        if(theMan == null) return false;
        session.setAttribute("chick",true);
        session.setAttribute("theMan",theMan);
        return true;
    }


    /**
     *  接口 3: 修改密码
     *
     *  name: /change_pass
     *
     *  method: post;
     *
     *  parameter: email,password;
     *
     *  return true/false;
     */
    @PostMapping("change_pass")
    public Boolean changePass(String email,String password,HttpSession session){
        Object check = session.getAttribute("check");
        if(check == null) return false;
        Human theMan = (Human)session.getAttribute("theMan");
        return commonService.updatePass(theMan,password);
    }

}
